// pages/coupon/detail.js
import api from '../../api/index'
import { AppId } from '../../api/config'
import { CHINA_NORTH_REGION } from '../../store/region'
import { userInfoStore } from '../../store/userInfo'
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLevel: 0,
    giftBag: null,

    maskHidden:false,

    pshow: false,
    cshow: false,
    dshow: false,
    plist: [],
    clist: [],
    dlist: [],
    privince: {},
    city: {},
    district: {},

    shoplist: [],
    selectshop:0,
    objectArray: CHINA_NORTH_REGION,

    rowId:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ 
      userLevel: userInfoStore.userInfo.level,
      rowId: options.id,
    })
    api.getGiftBagDetail({ rowId: options.id}).then(res=>{
      this.setData({ 
        giftBag:res.result
      });


    })
  },

  onShow: function () {
    
  },

  requestPayment: function (result) {
    wx.requestPayment({
      'timeStamp': result.timeStamp,
      'nonceStr': result.nonceStr,
      'package': result.package,
      'signType': result.signType,
      'paySign': result.paySign,
      'success': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付成功',
          showCancel: false,
          success: (res) => {
            wx.navigateTo({
              url: '/pages/clickMe/coupon/index?type=0',
            })
          }
        });
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: (res) => {
            
          }
        });
        return;
      },
      'complete': function (res) {
        console.log('complete===', res);
      }
    });
  },
  
  buy:function(){
    if(this.data.selectshop==0){
      this.setData({
        maskHidden: true
      });
      return;
    }
    let self=this;
    api.addRowCoupons({
      openId: userInfoStore.userInfo.openId,
      shopId: this.data.selectshop,
      rowId: this.data.rowId,
    }).then(res => {
      let { result } = res;
      if(result){
        self.requestPayment(result);
      }
    }, err => {
        wx.showToast({
          icon: "none",
          title: err
        })
      });
  },

  getPhoneNumber:function(e){
    // console.log(e);

    if (e.detail.iv) {
      let { session_key } = userInfoStore.userInfo;
      let pc = new WXBizDataCrypt(AppId, session_key);
      var ret = pc.decryptData(e.detail.encryptedData, e.detail.iv)
      console.log('解密后 data: ', ret)
      var param = {
        openId: userInfoStore.userInfo.openId,
        phone: ret.phoneNumber,
        level: 1
      }

      var self = this;
      if (app.globalData.inviteCode)
        param = Object.assign(param, { recomendCode: app.globalData.inviteCode })
      api.saveUser(param).then(res => {
        let { userInfo } = userInfoStore;
        let { result } = res;
        result.session_key = userInfo.session_key;
        userInfoStore.updateUserInfo(result);

        self.buy();

      }, err => {
        wx.showModal({
          title: "提交失败",
          content: err,
          showCancel: false,
          confirmText: "我知道了"
        })
      });
    }
  },

  radioChange: function (e) {
    this.setData({ selectshop: e.detail.value });
  },

  getShopList: function () {
    let param = {
      province: (this.data.privince.regname ? this.data.privince.regname : ''),
      city: (this.data.city.regname ? this.data.city.regname : ''),
      district: (this.data.district.regname ? this.data.district.regname : '')
    }
    let self = this;
    api.getshoplist(param).then(res => {
        self.setData({ shoplist: res.result, selectshop: 0 });

    });
  },

  selectByParid: function (pid) {
    let list = [];
    for (var i = 0; i < this.data.objectArray.length; i++) {
      if (this.data.objectArray[i].parid == pid) {
        list.push(this.data.objectArray[i])
      }
    }
    return list;
  },

  selectByParid1: function (pid) {
    let list = [];
    for (var i = 0; i < this.data.adrArray.length; i++) {
      if (this.data.adrArray[i].parid == pid) {
        list.push(this.data.adrArray[i])
      }
    }
    return list;
  },

  selectTap: function (e) {
    let idx = e.currentTarget.dataset.idx;
    if (idx == 1) {
      if (!this.data.pshow) {
        let list = this.selectByParid("1");
        this.setData({
          pshow: !this.data.pshow,
          plist: list,
          clist: [],
          dlist: [],
          privince: {},
          city: {},
          district: {}
        })
      } else {
        this.setData({
          pshow: !this.data.pshow
        })
      }
    }
    if (idx == 2 && this.data.privince.regid) {
      if (!this.data.cshow) {
        let list = this.selectByParid(this.data.privince.regid);
        this.setData({
          cshow: !this.data.cshow,
          clist: list,
          dlist: [],
          city: {},
          district: {}
        })
      } else {
        this.setData({
          cshow: !this.data.cshow
        })
      }
    }
    if (idx == 3 && this.data.city.regid) {
      if (!this.data.dshow) {
        let list = this.selectByParid(this.data.city.regid);
        this.setData({
          dshow: !this.data.dshow,
          dlist: list,
          district: {}
        })
      } else {
        this.setData({
          dshow: !this.data.dshow
        })
      }
    }
  },

  optionTap: function (e) {

    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let self = this;
    if (idx == 1) {
      this.setData({
        privince: this.data.plist[index],
        pshow: !this.data.pshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 2) {
      this.setData({
        city: this.data.clist[index],
        cshow: !this.data.cshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 3) {
      this.setData({
        district: this.data.dlist[index],
        dshow: !this.data.dshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
  },
  
})